﻿using EM.FrameWork;
using EM.FrameWork.Paging;
using EM.OA.BLL;
using EM.OA.DataModel.DBModel;
using EM.OA.Portal.Models;
using EM.OA.WebCommon;
using EM.OA.WebCommon.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;

namespace EM.OA.Portal.Controllers
{
    public class SignConfigController : BaseAuthController
    {
        /// <summary>
        /// 返回Index视图
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="page">当前页码</param>
        /// <param name="rows">每页条数</param>
        /// <returns></returns>
        public JsonResult GetList(string page, string rows)
        {
            List<object> result = new List<object>();
            SignConfigBLL bll = new SignConfigBLL();
            PagedList<EMOA_SignConfig> list = bll.GetPagedList(Convert.ToInt32(page), Convert.ToInt32(rows));
            list.ForEach(p =>
            {
                result.Add(new SignConfigModels().ToModel(p));
            });

            return ToJson(result, list.TotalItemCount);
        }


        /// <summary>
        /// 获取考勤名称列表，给combobox用
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCommboxList()
        {
            SignConfigBLL bll = new SignConfigBLL();

            List<EMOA_SignConfig> list = bll.GetList();
            string resultStr = "";
            resultStr += "[";
            foreach (EMOA_SignConfig item in list)
            {
                resultStr += "{";
                resultStr += string.Format("\"id\": \"{0}\", \"text\": \"{1}\", \"iconCls\": \"icon-ok\", \"state\": \"closed\"", item.SignConfigID.ToString(), item.SignName);
                resultStr += "},";
            }
            resultStr = resultStr.Substring(0, resultStr.Length - 1);
            resultStr += "]";
            return Content(resultStr);

        }

        /// <summary>
        /// 获取考勤明细jsonList
        /// </summary>
        /// <param name="signConfigID">考勤ID</param>
        /// <returns></returns>
        public ActionResult GetConfigDetailList(Guid signConfigID)
        {
            try
            {
                List<EMOA_SignConfigDetail> list = new List<EMOA_SignConfigDetail>();

                list = new SignConfigDetailBLL().GetList(p => p.SignConfigID == signConfigID, p => p.WorkBeginTime);
                string jsonFormInputItem = string.Empty;
                for (int i = 0; i < list.Count; i++) {
                    string openName = "txt_open" + i;
                    string offName = "txt_off" + i;
                    jsonFormInputItem += "{ \"name\": \"" + openName + "\", \"value\": \"" + list[i].WorkBeginTime.ToShortTimeString() + "\"},";
                    jsonFormInputItem += "{ \"name\": \"" + offName + "\", \"value\": \"" + list[i].WorkEndTime.ToShortTimeString() + "\"},";
                }

                if (!string.IsNullOrEmpty(jsonFormInputItem))
                {
                    jsonFormInputItem = "[" + jsonFormInputItem.Substring(0, jsonFormInputItem.Length - 1) + "]";
                    return Content(jsonFormInputItem);
                }
                else {
                    return Content("");
                }

            }
            catch (Exception ex)
            {

                return Content(ex.ToString());
            }
        }

        /// <summary>
        /// 增加实体
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(SignConfigModels model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    SignConfigBLL bll = new SignConfigBLL();
                    EMOA_SignConfig entity = model.ToEntity<EMOA_SignConfig>();
                    entity.SignConfigID = Guid.NewGuid();
                    // 工作日
                    //entity.WeekDays = GetWeekDays(model);
                    //考勤明细
                    List<EMOA_SignConfigDetail> list = new List<EMOA_SignConfigDetail>();
                    list = GetSignConfigDetailList(model.JsonConfigDetail,entity.SignConfigID);

                    if (bll.Add(entity) && new SignConfigDetailBLL().Add(list))
                    {
                        return Content("OK");
                    }
                    else
                    {
                        return Content("增加失败");
                    }
                }
                else
                    return Content("验证失败");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        /// <summary>
        /// 修改实体
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(SignConfigModels model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    SignConfigBLL bll = new SignConfigBLL();
                    EMOA_SignConfig entity = bll.GetEntity(model.SignConfigID);
                    entity = model.ToEntity<EMOA_SignConfig>(entity);
                    //工作日
                    //entity.WeekDays = GetWeekDays(model);

                    //考勤明细
                    List<EMOA_SignConfigDetail> list = new List<EMOA_SignConfigDetail>();
                    list = GetSignConfigDetailList(model.JsonConfigDetail, entity.SignConfigID);

                    if (bll.Update(entity) && new SignConfigDetailBLL().Delete(p => p.SignConfigID == model.SignConfigID) && new SignConfigDetailBLL().Add(list))
                        return Content("OK");
                    else
                        return Content("修改失败");
                }
                else
                {
                    return Content("验证失败");
                }
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        #region 获取考勤明细list
        private List<EMOA_SignConfigDetail> GetSignConfigDetailList(string jsonConfigDetail,Guid signConfigID)
        {
            List<EMOA_SignConfigDetail> list = new List<EMOA_SignConfigDetail>();
            if (!string.IsNullOrEmpty(jsonConfigDetail))
            {
                List<FormInputItem> listItemValues = new List<FormInputItem>();
                listItemValues = JsonHelper.GetFormValuesByInputItemIDs(jsonConfigDetail);
                int count = 0;
                count = (listItemValues.Count / 2) - 1;
                for (int i = 0; i <= count; i++)
                {
                    EMOA_SignConfigDetail entityDetail = new EMOA_SignConfigDetail();
                    entityDetail.SignConfigDetailID = Guid.NewGuid();
                    entityDetail.SignConfigID = signConfigID;

                    FormInputItem biginTime = listItemValues.Find(delegate(FormInputItem ft)
                    {
                        return ft.name == "txt_open" + i;
                    });

                    FormInputItem endTime = listItemValues.Find(delegate(FormInputItem ft)
                    {
                        return ft.name == "txt_off" + i;
                    });

                    entityDetail.WorkBeginTime = Convert.ToDateTime(biginTime.value);
                    entityDetail.WorkEndTime = Convert.ToDateTime(endTime.value);

                    list.Add(entityDetail);
                }
            }
            return list;
        }

        #endregion
        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delete(string id)
        {
            try
            {
                SignConfigBLL bll = new SignConfigBLL();
                if (bll.Delete(Guid.Parse(id)))
                    return Content("OK");
                else
                    return Content("删除失败");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

    }
}